import { getOssKey } from '../api/oss'
import COS from 'cos-js-sdk-v5'

const config = {
  Bucket: 'manager-1300279250',
  Region: 'ap-chengdu'
}

const cos = new COS({
  getAuthorization: function(option, callback) {
    getOssKey({
      Bucket: config.Bucket,
      Region: config.Region
    }).then(response => {
      const data = response.data
      const credentials = data && data.credentials
      if (!data || !credentials) { return console.error('签名错误') }
      callback({
        TmpSecretId: credentials.tmpSecretId,
        TmpSecretKey: credentials.tmpSecretKey,
        XCosSecurityToken: credentials.sessionToken,
        ExpiredTime: data.expiredTime
      })
    })
  }
})

export function createUniqueString() {
  const timestamp = +new Date() + ''
  const randomNum = parseInt((1 + Math.random()) * 65536) + ''
  return (+(randomNum + timestamp)).toString(32)
}

// /**
//  * 下载桶文件
//  */
// export function getObject() {
//   cos.getObject({
//     Bucket: config.Bucket,
//     Region: config.Region,
//     Key: 'coursemap_S100.png'
//   }, function(err, data) {
//     console.log(err || data.Body)
//   })
// }
//
// /**
//  * 获取桶文件URL
//  */
// export function getObjectUrl(name, callback) {
//   cos.getObjectUrl({
//     Bucket: config.Bucket,
//     Region: config.Region,
//     Key: name
//   }, (err, data) => {
//     callback(err, data)
//     // console.log(err || data.Url);
//   })
// }

export function putObejct(obj, pre, callback) {
  const extname = obj.name.substring(obj.name.lastIndexOf('.'), obj.length)
  const name = createUniqueString() + extname
  cos.putObject({
    Bucket: config.Bucket,
    Region: config.Region,
    Key: pre + '/' + name,
    StorageClass: 'STANDARD',
    Body: obj
  }, function(err, data) {
    if (err) console.log(err)
    callback(data)
  })
}
